package edu.sctu.xialei.june.day20150617one;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;

/**
 * Created by Administrator on 2015/6/16.
 */
public class TestUrl {

    private Scanner in = new Scanner(System.in);

    public void testUrl(String path) throws IOException {
        URL url = new URL(path);

        InputStream inputStream = url.openStream();

        byte[] buffer = new byte[1024];

        inputStream.read(buffer);

        System.out.println(new String(buffer, "utf-8"));
    }

    public void testUrlContent(String path) throws IOException {
        URL url = new URL(path);

        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

        httpURLConnection.connect();

        String headerField = String.valueOf(httpURLConnection.getInstanceFollowRedirects());

        System.out.println(headerField);
    }

    public void testUrlPost(String path) throws IOException {
        URL url = new URL(path);

        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setUseCaches(false);

        httpURLConnection.connect();

        OutputStream outputStream = httpURLConnection.getOutputStream();

        outputStream.write( ("one=" + in.next() ).getBytes() );
        outputStream.close();

        OutputStream outputStream1 = httpURLConnection.getOutputStream();

        outputStream1.write( ("one=" + in.next() ).getBytes() );
        outputStream1.close();

        byte[] buffer = new byte[ 2048];

        InputStream inputStream = httpURLConnection.getInputStream();
        inputStream.read(buffer);

        inputStream.close();

        System.out.println(new String(buffer));


        OutputStream outputStream2 = httpURLConnection.getOutputStream();

        outputStream2.write( ("one=" + in.next() ).getBytes() );
        outputStream2.close();

        InputStream inputStream1 = httpURLConnection.getInputStream();
        inputStream1.read(buffer);

        System.out.println(new String(buffer));

    }
}
